package cn.com.platform.web.manage.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import cn.com.easy.exception.BusinessException;
import cn.com.easy.permission.model.UserModel;
import cn.com.easy.permission.service.system.urlreserve.anotion.UrlReserveAnotion;
import cn.com.easy.permission.web.controller.BaseController;
import cn.com.easy.permission.web.dto.MessageDTO;
import cn.com.easy.permission.web.dto.PageRequestParamDTO;
import cn.com.easy.utils.Page;
import cn.com.easy.utils.PageUtils;
import cn.com.easy.utils.ResponseOutputUtils;
import cn.com.platform.dao.AdvDao;
import cn.com.platform.dao.AdvItemDao;
import cn.com.platform.entity.AdvertEntity;
import cn.com.platform.entity.AdvertItemEntity;
import cn.com.platform.mybatis.AdvItemMybatisDao;
import cn.com.platform.service.AdvService;
import cn.com.platform.utils.FileUtils;
import cn.com.platform.web.manage.dto.AdvItemDto;
import cn.com.platform.web.manage.dto.AdvItemQueryParamDto;

import com.github.miemiedev.mybatis.paginator.domain.PageList;

/***
 * 广告管理
 * 
 * @author chenbinghuang 2017年6月14日
 * 
 */
@Controller
@RequestMapping("/manage/adv/item")
public class AdvItemManageController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(AdvItemManageController.class);

	/** 广告Dao */
	@Autowired
	private AdvItemDao advItemDao;

	/** 广告位Dao */
	@Autowired
	private AdvDao advDao;

	/** 广告MybatisDao */
	@Autowired
	private AdvItemMybatisDao advItemMybatisDao;

	/** 广告服务类 */
	@Autowired
	private AdvService advService;

	/**
	 * 自动转换日期类型的字段格式
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
	}

	/***
	 * 广告管理
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @author chenbinghuang 2017年6月14日
	 */
	@UrlReserveAnotion("广告管理")
	@RequestMapping("")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "/manage/adv/adv_item";
	}

	/***
	 * 获取广告列表
	 * 
	 * @param req
	 * @param res
	 * @param paramDto
	 * @param param
	 * @author chenbinghuang 2017年6月14日
	 */
	@UrlReserveAnotion("获取广告列表")
	@RequestMapping("/list")
	public void getAllAdvItem(HttpServletRequest req, HttpServletResponse res, PageRequestParamDTO paramDto, final AdvItemQueryParamDto param) {
		try {
			if (paramDto.getSortOrder() == null) {
				paramDto.setSortName("id");
				paramDto.setSortOrder("desc");
			}
			PageList<AdvItemDto> pageObject = advItemMybatisDao.queryAdvItems(param, paramDto.buildMyBatisPageRequest());

			Page<AdvItemDto> page = PageUtils.getPage(pageObject);
			ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", true, page));
		} catch (Exception ex) {
			logger.error("获取所有广告异常.", ex);
			ResponseOutputUtils.renderJson(res, MessageDTO.newInstance("", false, "获取所有广告异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/***
	 * 保存或更新广告
	 * 
	 * @param request
	 * @param response
	 * @param file
	 * @param advItemDto
	 * @author chenbinghuang 2017年6月14日
	 */

	@UrlReserveAnotion("保存或..更新广告")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void saveOrUpdateRole(HttpServletRequest request, HttpServletResponse response, MultipartFile file, AdvItemDto advItemDto) {
		try {
			UserModel admin = getCurrentUser(request);
			if (admin == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}
			// 图片操作
			if (file != null && file.getSize() > 0) {
				advItemDto.setPhoto(FileUtils.picUpload(file, "photo/adv/advItemPicImg", this.getCurrentUser(request).getId()));
			}
			advService.saveOrUpdate(advItemDto, admin);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
		} catch (Exception ex) {
			logger.error("提交广告信息异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "提交广告信息异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/***
	 * 关闭/开启广告
	 * 
	 * @param request
	 * @param response
	 * @param advItemEntity
	 * @author chenbinghuang 2017年6月14日
	 */
	@UrlReserveAnotion("关闭/开启广告")
	@RequestMapping(value = "close")
	public void closeAdvItem(HttpServletRequest request, HttpServletResponse response, AdvertItemEntity advItemEntity) {
		try {
			UserModel admin = getCurrentUser(request);
			if (admin == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}
			if (advItemEntity.getId() == null || advItemEntity.getId() <= 0) {
				throw new BusinessException("未找到该内容");
			}
			AdvertItemEntity advItemEntityTemp = advItemDao.findByIdAndTitle(advItemEntity.getId(), advItemEntity.getTitle());
			if (advItemEntityTemp == null) {
				throw new BusinessException("未找到该内容");
			} else {
				if (advItemEntityTemp.isClosed() == true) {
					advItemEntityTemp.setClosed(false);
				} else {
					advItemEntityTemp.setClosed(true);
				}
				/* advItemEntityTemp.setLastModifyBy(admin.getLoginname()); */
				advItemEntityTemp.setLastModifyTime(new Date());
				advItemDao.save(advItemEntityTemp);
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
			}
		} catch (Exception ex) {
			logger.error("关闭/开启广告异常，id:" + advItemEntity.getTitle(), ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "关闭/开启广告异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/***
	 * 删除广告
	 * 
	 * @param request
	 * @param response
	 * @param advItemEntity
	 * @author chenbinghuang 2017年6月14日
	 */
	@UrlReserveAnotion("删除广告")
	@RequestMapping(value = "/delete")
	public void deleteAdvItem(HttpServletRequest request, HttpServletResponse response, AdvertItemEntity advItemEntity) {
		try {
			UserModel admin = getCurrentUser(request);
			if (admin == null) {
				throw new BusinessException("用户不存在，请重新登录");
			}
			// 删除广告
			if (advItemEntity.getId() == null || advItemEntity.getId() <= 0) {
				throw new BusinessException("未找到该内容");
			}
			AdvertItemEntity advItemEntityTemp = advItemDao.findByIdAndTitle(advItemEntity.getId(), advItemEntity.getTitle());
			if (advItemEntityTemp == null) {
				throw new BusinessException("未找到该内容");
			} else {
				advItemDao.delete(advItemEntityTemp.getId());
				ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, ""));
			}
		} catch (Exception ex) {
			logger.error("删除广告异常，id:" + advItemEntity.getTitle(), ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "删除广告异常.ex:" + ex.getLocalizedMessage()));
		}
	}

	/***
	 * 获取广告位
	 * 
	 * @param request
	 * @param response
	 * @author chenbinghuang 2017年6月14日
	 */
	@UrlReserveAnotion("获取广告位")
	@RequestMapping(value = "/findAdv")
	public void getAllAdv(HttpServletRequest request, HttpServletResponse response) {
		try {
			org.springframework.data.domain.Page<AdvertEntity> advPageEntities = advDao.findByDeleteStatus(false, null);

			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", true, advPageEntities.getContent()));
		} catch (Exception ex) {
			logger.error("获取广告位异常.", ex);
			ResponseOutputUtils.renderJson(response, MessageDTO.newInstance("", false, "获取广告位异常.ex:" + ex.getLocalizedMessage()));
		}
	}
}
